const Redis = require('ioredis');

class RedisUtils {
    constructor() {
        this.redis = new Redis({
            port: process.env.REDIS_PORT || 6379,
            host: process.env.REDIS_HOST || '127.0.0.1',
            password: process.env.REDIS_PASSWORD || '',
            db: process.env.REDIS_DB || 0
        });
    }

    /**
     * 设置Redis键值对
     * @param {string} key - 键
     * @param {string} value - 值
     * @param {number} expireTime - 过期时间（秒）
     * @returns {Promise<void>}
     */
    async set(key, value, expireTime = null) {
        try {
            if (expireTime) {
                await this.redis.set(key, value, 'EX', expireTime);
            } else {
                await this.redis.set(key, value);
            }
        } catch (err) {
            throw new Error(`Redis设置键值对失败: ${err.message}`);
        }
    }

    /**
     * 获取Redis键值对
     * @param {string} key - 键
     * @returns {Promise<string|null>}
     */
    async get(key) {
        try {
            return await this.redis.get(key);
        } catch (err) {
            throw new Error(`Redis获取键值失败: ${err.message}`);
        }
    }

    /**
     * 删除Redis键
     * @param {string} key - 键
     * @returns {Promise<void>}
     */
    async del(key) {
        try {
            await this.redis.del(key);
        } catch (err) {
            throw new Error(`Redis删除键失败: ${err.message}`);
        }
    }

    /**
     * 设置键的过期时间
     * @param {string} key - 键
     * @param {number} seconds - 过期时间（秒）
     * @returns {Promise<void>}
     */
    async expire(key, seconds) {
        try {
            await this.redis.expire(key, seconds);
        } catch (err) {
            throw new Error(`Redis设置过期时间失败: ${err.message}`);
        }
    }

    /**
     * 检查键是否存在
     * @param {string} key - 键
     * @returns {Promise<boolean>}
     */
    async exists(key) {
        try {
            const result = await this.redis.exists(key);
            return result === 1;
        } catch (err) {
            throw new Error(`Redis检查键是否存在失败: ${err.message}`);
        }
    }
}

// 导出Redis工具类的单例
module.exports = new RedisUtils();